<template>
	<view style="position: relative;" class="container text-df">
		<uni-search-bar v-model="bottom_param.productName" clearButton="auto" cancelButton="none" radius="20"
			@confirm="search" @clear="cancel_search" bgColor="#fff" placeholder="输入商品名称搜索">
		</uni-search-bar>
		<!-- <image src="https://api.anred.qrsk.net/applet/profile/image/exchange/exchangbg.png"
			style="width: 100%; height: 420rpx;" mode="aspectFill"></image> -->
		<view>
			<view class="l-pd-left20 l-pd-right20">
				<!-- 未登录状态 -->
				<view v-if="store.state.token==''" class="top_msg padding-com border-radius flex-row-ct"
					style="width: 100%;text-align: center;height: 98px;" @click="store.loginTip()">
					<image src="../../static/image/exchange/root.png" class="margin-right-xs"
						style="width: 16px;height: 16px;"></image>
					<text class="text-bold">请登录后查看积分余额</text>
				</view>
				<!-- 登录状态 -->
				<view v-else class="top_msg padding-com border-radius"
					style="display: flex;width: 100%;position: relative;height: 98px;">
					<view class="flex-column-st">
						<view class="theme-color margin-bottom-xs text-bold" style="font-size: 36px;">{{point}}
						</view>
						<view class="text-bold " style="opacity: 1; color: #464646;">可用积分</view>
					</view>
					<view class="" style="">
						<view class="flex-row" style="align-items: center;position: absolute;right: 20rpx;"
							@click="to_pointRecord">
							<text style="color: #aaa;">兑换记录</text>
							<uni-icons type="right" size="14" color="#aaa"></uni-icons>
						</view>
						<view class="border-radius-shadow  flex-row" @click="to_pointDetail"
							style="align-items: center;position: absolute;bottom: 20rpx;right: 30rpx;padding: 2rpx 22rpx;">
							<image src="https://api.anred.qrsk.net/applet/profile/image/exchange/detail.png"
								mode="aspectFill" style="width: 60rpx; height: 60rpx;"></image>
							<view class="flex-row margin-left-xs" style="line-height: 60rpx;">
								<view class="text-bold" style="color: #DB8300;">积分明细</view>
							</view>
						</view>
					</view>
				</view>
				<!-- <view class="border-radius padding-com bg-white">
					<view class="flex-row">
						<view>
							<view>我的积分:</view>
							<view
								style="height: 8px;width: 58px;margin-top: -6px;background: linear-gradient(to right,#FD7E0C,#FDBE16,#FEF8D7);border-radius: 4px 0 0 4px;">
							</view>
						</view>
						<view class="text-low margin-left-xs" v-if="store.state.token==''" @click="store.loginTip()">
							请登录...</view>
						<view class="text-bold text-lg margin-left-xs" v-else>{{point}}</view>
					</view>
				
					<view class="margin-top-sm flex-row-bt">
						<view class="border-radius-shadow padding-xs flex-row" @click="to_pointDetail"
							style="width: 48%; justify-content: center;">
							<image src="https://api.anred.qrsk.net/applet/profile/image/exchange/detail.png"
								mode="aspectFill" style="width: 60rpx; height: 60rpx;"></image>
							<view class="flex-row margin-left-xs" style="line-height: 60rpx;">
								<view>积分明细</view>
								<uni-icons type="right" size="16" color="#aaa"></uni-icons>
							</view>
						</view>
						<view class="border-radius-shadow padding-xs flex-row" @click="to_pointRecord"
							style="width: 48%; justify-content: center;">
							<image src="https://api.anred.qrsk.net/applet/profile/image/exchange/record.png"
								mode="aspectFill" style="width: 60rpx; height: 60rpx;"></image>
							<view class="flex-row margin-left-xs" style="line-height: 60rpx;">
								<view>兑换记录</view>
								<uni-icons type="right" size="16" color="#aaa"></uni-icons>
							</view>
						</view>
					</view>
				</view> -->
				
				<view class="bg-white padding-com margin-top-sm border-radius" v-if="wait_open.length!=0">
					<view class="margin-bottom-sm flex-row-bt">
						<view class="flex-row">
							<view style="" class="vertical-line theme-bg-color"></view>
							<text class="text-lg margin-left-xs" style="">即将开放</text>
						</view>
					</view>
				
					<scroll-view scroll-x="true" class=""
						style="height: 420rpx;white-space: nowrap;box-sizing: border-box;padding: 0 10rpx;">
						<view v-for="(item,index) in wait_open" :key="index" class="border-radius-shadow margin-right-xs"
							style="display: inline-block;width: 270rpx;height: 400rpx;" @click="toDetail(item.id)">
							<image class="" :src="imgURL+item.indexImg" mode="aspectFill"
								style="width: 270rpx;height: 180rpx;border-radius: 30rpx 30rpx 0 0;">
							</image>
							<view class=" " style="padding: 10rpx;">
								<view>{{item.productName}}</view>
								<view class="theme-color text-bold" style="margin-top: 10rpx;">{{item.integratedWorth}}积分
								</view>
								<view style="margin-top: 10rpx;">
									<text class="text-sm">剩余库存：</text>
									<text class="theme-color">{{item.inventory}}</text>
								</view>
								<!-- <view v-if="item.remark.time==0" style="margin-top: 10rpx;"
									class="theme-color text-sm">请下拉刷新</view> -->
								<view class="flex-row" style="margin-top: 10rpx;" v-if="item.remark.time>0">
									<uni-countdown :day="item.remark.day" :hour="item.remark.hour"
										:minute="item.remark.minu" :second="item.remark.sec" color="#EE3F4D" :font-size="12"
										@timeup="timeup(index,item.id)" />
									<view class="text-sm">后</view>
								</view>
								<!-- <view class="text-sm" style="margin-top: 10rpx;">{{item.time}}后兑换</view> -->
							</view>
						</view>
					</scroll-view>
				</view>
				
				<view class="bg-white padding-tb-com margin-top-sm border-radius l-pd-left20 l-pd-right20">
				
					<!-- <uni-search-bar v-model="bottom_param.productName" clearButton="auto" cancelButton="none" radius="20"
						@confirm="search" @clear="cancel_search">
					</uni-search-bar> -->
					<zb-tab :scrollable="true" :shrink="true" lineColor="#EE3F4D" :lineWidth="20"
						:activeStyle="{
					    fontWeight: 'bold',
					    transform: 'scale(1.2)',
						color:'#EE3F4D'
					    }" :data="select.list2" v-model="bottom_param.categoryId" @change="change_tab">
					</zb-tab>
					<filter-shop :current="0" :list="select.list" v-on:select_change="select_change"></filter-shop>
				</view>
			</view>

			<view class="waterfall margin-top-sm">
				<!-- v-if="waterfall.show" -->
				<uv-waterfall  ref="Waterfall" v-model="waterfall.list" :add-time="10"
					:left-gap="waterfall.leftGap" :right-gap="waterfall.rightGap" :column-gap="waterfall.columnGap"
					@changeList="changeList">
					<!-- 第一列数据 -->
					<template v-slot:list1>
						<!-- 为了磨平部分平台的BUG，必须套一层view -->
						<view>
							<view v-for="(item, index) in waterfall.list1" :key="item.id" @click="toDetail(item.id)"
								class="waterfall-item border-radius-shadow bg-white">
								<image class="waterfall-item__image" :src="imgURL+item.indexImg" mode="widthFix" :style="getWidth(item)"></image>
								<view class="waterfall-item__ft">
									<view class="">{{item.productName}}</view>
									<view class="text-bold theme-color text-lg margin-top-xs">{{item.integratedWorth}}积分
									</view>
									<view class="margin-top-xs">
										<text class="text-sm">剩余库存：</text>
										<text class="text-bold theme-color text-lg">{{item.inventory}}</text>
									</view>
								</view>
							</view>
						</view>
					</template>
					<!-- 第二列数据 -->
					<template v-slot:list2>
						<!-- 为了磨平部分平台的BUG，必须套一层view -->
						<view>
							<view v-for="(item, index) in waterfall.list2" :key="item.id" @click="toDetail(item.id)"
								class="waterfall-item border-radius-shadow bg-white">
								<image class="waterfall-item__image" :src="imgURL+item.indexImg" mode="widthFix" :style="getWidth(item)"></image>
								<view class="waterfall-item__ft">
									<view class="">{{item.productName}}</view>
									<view class="text-bold theme-color text-lg margin-top-xs">{{item.integratedWorth}}积分
									</view>
									<view class="margin-top-xs">
										<text class="text-sm">剩余库存：</text>
										<text class="text-bold theme-color text-lg">{{item.inventory}}</text>
									</view>
								</view>
							</view>
						</view>
					</template>
				</uv-waterfall>
			</view>
			<uni-load-more :status="loadStatus" :contentText="{
				contentnomore: '我是有底线的~'
			}"></uni-load-more>
		</view>
	</view>
	<!-- 接口请求加载动画 -->
	<loading></loading>
</template>

<script setup lang="ts">
	import { nextTick, reactive, ref } from 'vue';
	import { onReachBottom, onLoad, onPullDownRefresh, onShow } from "@dcloudio/uni-app"
	import { getExchangeProduct, getlistseon, getProductList, updateStatus } from '../../api/exchange/exchange';
	import { imgURL } from '../../api/request';
	import { getRestTime } from '../../utils/time';
	import store from '../../store/login';
	import { getPointsDetails } from '../../api/point/point';

	const wait_open = ref([])
	// 
	const select = reactive({
		// input: '',
		list: [{
			name: '综合',
			isLifting: false //是否升降排序
		}, {
			name: '销量',
			isLifting: false //是否升降排序
		}, {
			name: '价格',
			isLifting: true //是否升降排序
		}],
		list2: []
	})
	const waterfall = reactive({
		list: [],// 瀑布流全部数据
		list1: [],// 瀑布流第一列数据
		list2: [],// 瀑布流第二列数据
		leftGap: 15,
		rightGap: 15,
		columnGap: 15,
		show: false
	})
	
	//请求上架商品参数
	const bottom_param = reactive({
		categoryId: 1,
		productName: '',
		current: 1,
		size: 6
	})

	// 积分
	const point = ref('')

	const Waterfall = ref(null)
	
	const total = ref(0)
	const loadStatus = ref('loading')

	onShow(() => {
		if (store.state.token != '') {
			getPointsDetails().then((res : any) => {
				point.value = res.data.pointer
				uni.setStorageSync('point', point.value)
				store.state.point = point.value
			})
		}
	})

	onLoad(() => {
		// 请求上架商品
		getExchangeProductList()
		//待上架商品
		get_waitProduct()
		// 获取商品的分类
		getListseont()
	})
	//触底刷新
	onReachBottom(() => {
		if(waterfall.list.length >= total.value) return
		bottom_param.current++
		getExchangeProductList()
	})

	// 下拉刷新
	onPullDownRefresh(() => {
		bottom_param.current = 1
		waterfall.list = [];
		Waterfall.value.clear();
		waterfall.list1 = [];
		waterfall.list2 = [];
		getExchangeProductList()
		//待上架商品
		get_waitProduct()
	})
	const getListseont = () => {
		getlistseon().then(res => {
			for (let i = 0; i < res.data.length; i++) {
				select.list2.push({
					name: res.data[i].categoryName,
					value: res.data[i].id
				})
			}
			console.log(select.list2)
		})
	}
	const change_tab = () => {
		bottom_param.current = 1
		waterfall.list = [];
		Waterfall.value.clear();
		waterfall.list1 = [];
		waterfall.list2 = [];
		getExchangeProductList()
	}

	//待上架商品
	const get_waitProduct = () => {
		wait_open.value = []
		getProductList().then((res : any) => {
			for (let i = 0; i < res.data.length; i++) {
				wait_open.value.push(res.data[i])
				wait_open.value[i].remark = getRestTime(wait_open.value[i].releaseTime)
				if (wait_open.value[i].remark.time <= 0) {
					timeup(i, wait_open.value[i].id)
				}
			}
		})
	}

	//修改待上架商品状态
	const timeup = (index : any, productId : any) => {
		productId = parseInt(productId)
		wait_open.value[index].remark.time = 0
		updateStatus({ productId }).then((res : any) => {
			console.log(res.msg)
		})
	}

	//搜索
	const search = () => {
		bottom_param.current = 1
		waterfall.list = [];
		Waterfall.value.clear();
		waterfall.list1 = [];
		waterfall.list2 = [];
		getExchangeProductList()
	}

	//取消搜索
	const cancel_search = () => {
		bottom_param.current = 1
		bottom_param.productName = ''
		waterfall.list = [];
		Waterfall.value.clear();
		waterfall.list1 = [];
		waterfall.list2 = [];
		getExchangeProductList()
	}

	// 这点非常重要：e.name在这里返回是list1或list2，要手动将数据追加到相应列
	const changeList = (e) => {
		waterfall[e.name].push(e.value);
	}
	// 获取商品列表
	const getExchangeProductList = () => {
		loadStatus.value = 'loading'
		getExchangeProduct(bottom_param).then(async (res : any) => {
			uni.stopPullDownRefresh();
			total.value = res.data.total
			let list = res.data.list
			// 目前图片加载太慢不适用
			// for (let i = 0; i < list.length; i++) {
			// 	const imageInfo = await getImageInfo(imgURL + list[i].indexImg)
			// 	list[i].w = imageInfo.w
			// 	list[i].h = imageInfo.h
			// }
			nextTick(()=> {
				loadStatus.value = 'more'
				if(waterfall.list.length >= total.value){
					loadStatus.value = 'no-more'
				}
			})
			if(bottom_param.current === 1) {
				waterfall.list = list
			}else {
				waterfall.list = waterfall.list.concat(list)
			}
		})
	}
	// 获取图片信息
	const getImageInfo = (url: string) => {
		return new Promise((resolve,reject) => {
			// 默认图片宽高
			const defaultWH = {
				w: 165,
				h: 0
			}
			try{
				// #ifdef MP-WEIXIN
				wx.getImageInfo({
					src: url,
					success: (e) => {
						const v = uni.upx2px(750) - waterfall.leftGap - waterfall.rightGap - waterfall.columnGap;
						const w = v/2;
						const rate = w / e.width;
						const h = rate* e.height;
						resolve({
							w,
							h
						})
					},
					fail: () => {
						resolve(defaultWH)
					}
				})
				// #endif
				// #ifndef MP-WEIXIN
				const image = new Image();
				image.src = url;
				image.onload = function() {
					const v = uni.upx2px(750) - waterfall.leftGap - waterfall.rightGap - waterfall.columnGap;
					const w = v/2;
					const rate = w / image.width;
					const h = rate* image.height;
					resolve({
						w,
						h
					})
				};
				image.onerror = function() {
					resolve(defaultWH)
				}
				// #endif
			}catch(e){
				//TODO handle the exception
				resolve(defaultWH)
			}
			
		})
	}
	// 积分明细
	const to_pointDetail = () => {
		if (store.state.token != '') {
			uni.navigateTo({
				url: '/pages/exchange/point_detail'
			})
		} else {
			//登录提示
			store.loginTip()
		}
	}

	// 兑换记录
	const to_pointRecord = () => {
		if (store.state.token != '') {
			uni.navigateTo({
				url: '/pages/exchange/point_record'
			})
		} else {
			//登录提示
			store.loginTip()
		}
	}

	const select_change = (e) => {
		console.log(JSON.stringify(e))
	}

	// 跳转详情
	const toDetail = (id : string) => {
		uni.navigateTo({
			url: '/pages/exchange/detail?id=' + id
		})
	}
	// 图片宽高样式
	const getStyle = (item: any) => {
		if(item.h === 0 || item.w === 0) return ''
		return {
			height: item.h + 'px',
			width: item.w + 'px'
		}
	}
	// 图片宽
	const getWidth = (item: any) => {
		if(item.w && item.w === 0) return ''
		return {
			width: item.w + 'px'
		}
	}
</script>

<style scoped lang="scss">
	@import '@/uni_modules/uv-ui-tools/libs/css/variable.scss';

	$show-lines: 1;
	page {
		background-color: #f7f7f7;
	}
	.container {
		padding-bottom: 60rpx;
		box-sizing: border-box;
		::-webkit-scrollbar {
			display: none;
			width: 0;
			height: 0;
			color: transparent;
		}
	}

	.top_msg {
		background: linear-gradient(164deg, #FFEEE3 4%, #FFFCFA 46%, #FFFFFF 172%);
	}

	.waterfall-item {
		overflow: hidden;
		margin-bottom: 30rpx;
		border-radius: 6px;
		&__image {
			width: 330rpx;
		}
	}

	.waterfall-item__ft {
		padding: 20rpx;
		background: #fff;
	}
</style>